<?php


namespace app\index\model;


use app\index\common\Common;
use app\index\controller\PaypalApi;
use Exception;
use RuntimeException;
use think\Model;

class Order extends Model
{
    public static $pay_type_list=[0=>'未生成账单',1=>'待发账单',2=>'待付款',3=>'部分付款',4=>'已付款',5=>'已取消',7=>'已退款',6=>'部分退款'];
    public static $logistics_status_list=[0=>'等待库存',1=>'待发货',2=>'已打单,待出库',3=>'已打单,已出库',4=>'已发货'];

    public function getPayTypeTextAttr ($value, $data) :string
    {
        $str = self::$pay_type_list;
        return $str[$data['pay_type']];
    }

    public function getShipStatusTextAttr ($value, $data) :string
    {
        $str='';
        if($data['logistics_status']===0) {
            $str = '等待库存';
        }elseif ($data['logistics_status']===1&&$data['waybill_id']===null){
            $str = '待发货';
        }elseif ($data['logistics_status']===1&&$data['waybill_id']!==null&&$data['stock_status']===1){
            $str = '已打单,待出库';
        }elseif ($data['logistics_status']===1&&$data['waybill_id']!==null&&$data['stock_status']===2){
            $str = '已打单,已出库';
        }elseif ($data['logistics_status']===2){
            $str = '已发货';
        }
        return $str;
    }

    public static function createOrder($order,$order_item,$ids): array
    {
        $OrderClass=new self();
        $CustomerOrderClass=new CustomerOrder();
        $OrderItemClass=new OrderItem();
        $OrderHistoryClass=new OrderHistory();
        $OrderItemDetailClass=new OrderItemDetail();

        $OrderClass->startTrans();
        try {
            $result=$CustomerOrderClass->whereIn('id',$ids)->update(['status'=>1]);
            if($result===false){
                return ['status'=>false,'result'=>'修改已订商品状态失败'];
            }

            /*$count = $OrderClass->where('customer_id',$order['customer_id'])->count();
            if($count == 0){
                $CustomerTrackRecordClass->content = '查看邮箱信息以及催款';
                $CustomerTrackRecordClass->customer_id = $order['customer_id'];
                $CustomerTrackRecordClass->status = 0;
                $CustomerTrackRecordClass->create_user = $order['create_user'];
                $CustomerTrackRecordClass->appointment_time = date('Y-m-d H:i:s',strtotime('+1 day'));
                $result = $CustomerTrackRecordClass->save();
                if($result===false){
                    return ['status'=>false,'result'=>'保存跟进订单失败'];
                }
                $result = $CustomerClass->where('id',$order['customer_id'])->update(['last_track_time'=>$CustomerTrackRecordClass->appointment_time]);
                if($result===false){
                    return ['status'=>false,'result'=>'刷新用户信息失败'];
                }
            }*/

            $OrderClass->data($order);
            $result=$OrderClass->save();
            if($result===false){
                return ['status'=>false,'result'=>'保存订单失败'];
            }
            $order_id=$OrderClass->id;

            if($order['amount_discount']>0) {
                $customer_discount=CustomerDiscount::where('customer_id', $order['customer_id'])->field('id,balance')->find();
                if(!empty($customer_discount)){
                    $customer_discount['balance']=round($customer_discount['balance']-$order['amount_discount'],2);
                    if($customer_discount['balance']<0){
                        $customer_discount['balance']=0;
                    }
                    $result=CustomerDiscount::where('id', $customer_discount['id'])->update(['balance'=>$customer_discount['balance']]);
                    if($result===false){
                        return ['status'=>false,'result'=>'抵扣更新记录失败'];
                    }
                    $result=(new CustomerDiscountHistory)->save(['discount_id'=>$customer_discount['id'],'order_id'=>$order_id,'customer_id'=>$order['customer_id'],'price'=>$order['amount_discount'],'type'=>0,'create_user'=>$order['create_user']]);
                    if($result===false){
                        return ['status'=>false,'result'=>'抵扣更新记录失败'];
                    }
                }
            }

            $order_item_insert=[];
            $order_item_detail=[];
            $history = ['order_id' => $order_id, 'operator' => session('Login_user')['id'], 'operational' => '创建订单.金额：'.$order['total_price'].'USD'];
            foreach ($order_item as $i => $item) {
                $item['order_id'] = $order_id;
                $item['show_index'] = $i + 1;
                if($item['gift'] === 1){
                    $item['gift'] = 2;
                }
                if(!empty($item['detail'])) {
                    $order_item_detail[$i] = $item['detail'];
                }
                unset($item['detail']);
                $order_item_insert[$i] = $item;
            }

            $result=$OrderHistoryClass->save($history);
            if($result===false){
                return ['status'=>false,'result'=>'历史记录失败'];
            }
            $result=$OrderItemClass->saveAll($order_item_insert);
            if($result===false){
                return ['status'=>false,'result'=>'保存订单商品失败'];
            }
            $order_item_detail_insert=[];
            foreach ($result as $key=>$value){
                if(isset($order_item_detail[$key])){
                    foreach ($order_item_detail[$key] as $item) {
                        $item['order_item_id']=$value->id;
                        $order_item_detail_insert[] = $item;
                    }
                }
            }
            if(!empty($order_item_detail_insert)) {
                $result = $OrderItemDetailClass->insertAll($order_item_detail_insert);
                if($result===false){
                    return ['status'=>false,'result'=>'保存订单商品详情失败'];
                }
            }

            $order=$OrderClass::getOrderById($order_id);
            $items=$OrderItemClass::getOrderItemsById($order_id);
            $order['items']=$items;

            ['status'=>$status,'result'=>$result]=PaypalApi::createInvoice($order);
            if($status===false){
                return ['status'=>false,'result'=>$result];
            }
            $invoice_id=$result['id'];
            $result=$OrderClass->where('id',$order_id)->update(['receipt_number'=>$invoice_id,'pay_type'=>1]);
            if($result===false){
                return ['status'=>false,'result'=>'创建账单失败'];
            }

            $OrderClass->commit();
            return ['status'=>true,'result'=>['msg'=>'创建账单成功','id'=>$order_id]];
        }catch (Exception $e) {
            $OrderClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'添加失败'.$e->getMessage()];
        }
    }

    public static function getList($search_param,$page_param): array{
        $OrderClass=new self();
        $customerClass=new Customer();
        $orderItemClass=new OrderItem();
        $orderItemDetailClass=new OrderItemDetail();
        $where['o.del_flag']=['=',0];

        ['action_role'=>$action_role,'search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');
        if(!empty($group)){
            $where['o.create_group']=['=',$group];
        }else if (is_numeric($search_param['group_id']) && $search_param['group_id']) {
            $where['o.create_group'] = ['=', $search_param['group_id']];
        }

        if(!empty($search_user)) {
            $where['o.create_user'] = ['in', $search_user];
        }else if(is_numeric($search_param['user_id'])){
            $search_user=[$search_param['user_id']];
            $where['o.create_user'] = ['in', $search_user];
        }

        if (is_numeric($search_param['pay_type'])) {
            $where['o.pay_type']=['=',$search_param['pay_type']];
            if($search_param['pay_type']==5){
                $where['o.order_status']=['=',2];
            }else{
                $where['o.order_status']=['=',1];
            }
        }
        if(is_numeric($search_param['logistics_status'])){
            switch ($search_param['logistics_status']){
                case 0:
                    $where['o.logistics_status']=['=',$search_param['logistics_status']];
                    break;
                case 1:
                    $where['o.logistics_status']=['=',$search_param['logistics_status']];
                    $where['o.waybill_id']=['null',''];
                    break;
                case 2:
                    $where['o.logistics_status']=['=',1];
                    $where['o.stock_status']=['=',1];
                    $where['o.waybill_id']=['not null',''];
                    break;
                case 3:
                    $where['o.logistics_status']=['=',1];
                    $where['o.stock_status']=['=',2];
                    $where['o.waybill_id']=['not null',''];
                    break;
                case 4:
                    $where['o.logistics_status']=['=',2];
                    break;
            }
        }
        if ($search_param['customer_id']) {
            $where['o.customer_id']=['=',$search_param['customer_id']];
        }
        if (!empty($search_param['create_time'])) {
            $where['o.create_time']=['between',[$search_param['create_time'].' 00:00:00',$search_param['create_time'].' 23:59:59']];
        }
        if(is_numeric($search_param['track'])){
            $search_param['track']=(int)$search_param['track'];
            if($search_param['track']===0) {
                $where['o.track_end_times'] = ['=',0];
                $where['o.last_track_time']= null;
            }elseif($search_param['track']===1){
                $where['o.last_track_time'] = ['<', date('Y-m-d') . ' 23:59:59'];
            }elseif($search_param['track']===2){
                $where['o.last_track_time'] = ['>', date('Y-m-d') . ' 23:59:59'];
            }elseif($search_param['track']===3){
                $where['o.last_track_time']= null;
                $where['o.track_end_times'] = ['>',0];
            }
        }
        if (!empty($search_param['payment_time'])) {
            $where['o.payment_time']=['between',[$search_param['payment_time'].' 00:00:00',$search_param['payment_time'].' 23:59:59']];
        }
        if (!empty($search_param['search_key']) && !empty($search_param['search_value'])) {
            if($search_param['search_key']==='order_id'){
                $order_id=explode(' ',$search_param['search_value']);
                $where['o.order_id']=['in',$order_id];
            }elseif ($search_param['search_key']==='cn_name'||$search_param['search_key']==='en_name'){
                if (is_numeric($search_param['selling_price'])) {
                    $price['selling_price']=['=',$search_param['selling_price']];
                }else{
                    $price=[];
                }
                $oi_id=$orderItemDetailClass->where($search_param['search_key'],'like','%'.$search_param['search_value'].'%')->where('del_flag',0)->column('order_item_id');
                $o_id=$orderItemClass->where(function ($query)use ($search_param,$oi_id){
                    $query->where($search_param['search_key'],'like','%'.$search_param['search_value'].'%')
                        ->whereOr('id','in',$oi_id);
                })->where($price)->where('del_flag',0)->column('order_id');
                $where['o.id'] =['in', $o_id];
            }elseif($search_param['search_key']==='email') {
                $where['c.'.$search_param['search_key']] = ['=', $search_param['search_value']];
            }else {
                $where['o.'.$search_param['search_key']] = ['=', $search_param['search_value']];
            }
        }
        $track_record_sql = CustomerTrackRecord::where('order_id =o.id')->where('del_flag',0)->field('content')->order('create_time desc')->limit(1)->buildSql();
        $obj=$OrderClass->alias('o')->where($where)
            ->join('customer c','o.customer_id=c.id','left')
            ->join('waybill w','o.waybill_id=w.id','left')
            ->field('o.id,o.order_id,o.receipt_number,o.total_price,o.amount_discount,o.logistics_status,o.amount_paid,o.user_name,c.nick_name,o.create_time,o.payment_time,o.pay_type,w.ship_no,o.waybill_id,o.stock_status,o.customer_id,o.remark,'.$track_record_sql.' content,o.last_track_time,o.track_end_times')
            ->order('o.create_time','desc')
            ->paginate($page_param['page_size'],false,['page'=>$page_param['page_num']]);

        if($obj->isEmpty()){
            return ['status'=>true,'result'=>['order'=>[],'total'=>0,'action_role'=>$action_role]];
        }
        $rows=$customerClass->column('type','id');
        $count=$obj->total();
        $data=$obj->items();
        $track_remind_timestamp=strtotime(date('Y-m-d') . ' 23:59:59');
        foreach($data as $key=>$value){
            $data[$key]['pay_type_text']=$obj[$key]->PayTypeText;
            $data[$key]['logistics_status_text'] = $obj[$key]->ShipStatusText;
            if($value['logistics_status']===0) {
                $data[$key]['logistics_tag_type']='warning';
                $data[$key]['logistics_tag_color']='';
            }elseif ($value['logistics_status']===1&&$value['waybill_id']===null){
                $data[$key]['logistics_tag_type']='info';
                $data[$key]['logistics_tag_color']='#ea4e4e';
            }elseif ($value['logistics_status']===1&&$value['waybill_id']!==null&&$value['stock_status']===1){
                $data[$key]['logistics_tag_type']='';
                $data[$key]['logistics_tag_color']='';
            }elseif ($value['logistics_status']===1&&$value['stock_status']===2){
                $data[$key]['logistics_tag_type']='info';
                $data[$key]['logistics_tag_color']='#67c23a';
            }elseif ($value['logistics_status']===2){
                $data[$key]['logistics_tag_type']='success';
                $data[$key]['logistics_tag_color']='';
            }
            if($value['receipt_number'] && $value['pay_type']!==0) {
//                $data[$key]['pdf_url'] = PAYPAL_PDF . '/invoice/actions/render-pdf/' . $value['receipt_number'] . '?removeQr=true';
                $data[$key]['pdf_url'] = DOMAIN_HOST.'/image/invoice/print?id='.$value['id'];
            }else{
                $data[$key]['pdf_url']='';
            }
            if (isset($rows[$value['customer_id']])){
                if ($rows[$value['customer_id']]==0){
                    $data[$key]['type_cn']='普通';
                }else{
                    $data[$key]['type_cn']='会员';
                }
            }
            $last_track_time=strtotime($value['last_track_time']);
            $data[$key]['need_track']=false;
            $data[$key]['track_type']=0;
            if($last_track_time) {
                if ((time() -$last_track_time) > (24 * 60 * 60)) {
                    $data[$key]['need_track'] = true;
                }
                if($last_track_time>$track_remind_timestamp){
                    $data[$key]['track_type']=2;
                }else{
                    $data[$key]['track_type']=1;
                }
            }else{
                if($value['track_end_times']>0){
                    $data[$key]['track_type']=3;
                }
            }
            $data[$key]['create_time']=explode(' ',$value['create_time'])[0];
            $data[$key]['real_price']=round($value['total_price']-$value['amount_discount'],2);
            $data[$key]['payment_time']=explode(' ',$value['payment_time'])[0];
            $data[$key]['curr']='USD';
        }
        return ['status'=>true,'result'=>['order'=>$data,'total'=>$count,'action_role'=>$action_role]];
    }

    public static function cancelOrder($id): array
    {
        $OrderClass=new self();
        $OrderItemClass=new OrderItem();
        $ProductClass=new Product();
        $OrderHistoryClass=new OrderHistory();
        $OrderItemDetailClass=new OrderItemDetail();

        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');
        if(!empty($group)){
            $where['create_group']=['=',$group];
        }

        if(!empty($search_user)) {
            $where['create_user'] = ['in', $search_user];
        }
        $where['id']=['=',$id];
        $where['order_status']=['=',1];
        $order=$OrderClass->where($where)->field('pay_type,receipt_number,create_group')->find();
        if(empty($order)){
            return ['status'=>false,'result'=>'未找到订单'];
        }


        $OrderClass->startTrans();
        try {
            $pro_ids=[];
            $old_item_data=$OrderItemClass->where('order_id',$id)->where('del_flag',0)->lock(true) ->field('amount,demand_stock,pro_id,id')->select()->toArray();
            $old_item_list=[];
            $old_item_id=[];
            foreach ($old_item_data as $key=>$value){
                if(!$value['pro_id']){
                    $old_item_id[]=$value['id'];
                }else{
                    $pro_ids[]=$value['pro_id'];
                }
                if(isset($old_item_list[$value['pro_id']])){
                    $old_item_list[$value['pro_id']]['amount']+=$value['amount'];
                    $old_item_list[$value['pro_id']]['demand_stock']+=$value['demand_stock'];
                    continue;
                }
                $old_item_list[$value['pro_id']]['amount']=$value['amount'];
                $old_item_list[$value['pro_id']]['demand_stock']=$value['demand_stock'];
            }
            if(!empty($old_item_id)) {
                $old_item_detail_list = $OrderItemDetailClass->where('order_item_id', 'in', $old_item_id)->where('del_flag', 0)->lock(true)->group('pro_id')->column('sum(amount) amount,sum(demand_stock) demand_stock', 'pro_id');
                if(!empty($old_item_detail_list)) {
                    $old_pro_ids = array_keys($old_item_detail_list);
                    $pro_ids = array_unique(array_merge($pro_ids, $old_pro_ids));
                }
            }
            $stock_list=$ProductClass->where('id','in',$pro_ids)->lock(true)->column('amount,demand_stock,locked_demand_stock,type','id');
            foreach ($stock_list as $key=>$value){
                if($value['type']===1) {
                    if (isset($old_item_list[$value['id']])) {
                        $value['demand_stock'] -= $old_item_list[$value['id']]['amount'];
                        $value['locked_demand_stock'] -= $old_item_list[$value['id']]['demand_stock'];
                    }
                    if (isset($old_item_detail_list[$value['id']])) {
                        $value['demand_stock'] -= $old_item_detail_list[$value['id']]['amount'];
                        $value['locked_demand_stock'] -= $old_item_detail_list[$value['id']]['demand_stock'];
                    }
                }
                $stock_list[$key]=$value;
            }

            if ($order['pay_type'] === 2) {
                ['status'=>$status,'result'=>$result]=PaypalApi::cancelInvoice($order['receipt_number'],$order['create_group']);
                if($status===false){
                    throw Exception('取消账单失败'.$result);
                }
                $update=['order_status' => 2,'pay_type'=>5];
            } else if ($order['pay_type'] === 1) {
                ['status'=>$status,'result'=>$result]=PaypalApi::deleteInvoice($order['receipt_number'],$order['create_group']);
                if($status===false){
                    throw Exception('删除账单失败'.$result);
                }
                $update=['order_status' => 2,'receipt_number'=>'','pay_type'=>5];
            }

            $result=$ProductClass->isUpdate()->allowField(['id','demand_stock','locked_demand_stock'])->saveAll($stock_list);
            if($result===false){
                throw Exception('回退库存失败');
            }
            $result=$OrderHistoryClass->insert(['order_id'=>$id,'operator'=>session('Login_user')['id'],'operational'=>'取消订单']);
            if($result===false){
                throw Exception('历史记录失败');
            }

            $result=$OrderClass->save($update,['id'=>$id]);
            if($result===false){
                return ['status'=>false,'result'=>'修改状态失败'];
            }
            $OrderClass->commit();
            return ['status'=>true,'result'=>$pro_ids];
        }catch (Exception $e) {
            $OrderClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'取消失败'.$e->getMessage()];
        }

    }

    public static function getOrderById($id,$type=1){
        $OrderClass=new self();

        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');

        if(!empty($search_user)){
            $where['o.create_user']=['in',$search_user];
        }
        if(!empty($group)){
            $where['o.create_group']=['=',$group];
        }
        $where['o.id']=['=',$id];
        $where['o.del_flag']=['=',0];
        if($type) {
            $where['o.order_status'] = ['=', 1];
        }

        $order=$OrderClass->alias(' o')
            ->join('__CUSTOMER__ cu','o.customer_id=cu.id','left')
            ->join('__COUNTRY__ c','o.country=c.id','left')
            ->join('__WAYBILL__ w','o.waybill_id=w.id','left')
            ->join('logistics l','w.logistics_id=l.id','left')
            ->where($where)
            ->field('o.order_id,o.receipt_number,o.stock_status,o.logistics_status,o.user_name,o.customer_id,o.email,o.country,o.city,o.address,o.zip_code,o.phone,o.payment_type,o.email,o.cc_email,o.items_price,o.ship_fee,o.total_price,o.tip,o.payment_type,o.partial_pay,o.pay_type,o.amount_discount,o.amount_paid,o.amount_refund,o.tip_paid,c.country_code,c.phone_code,c.country_en_name,o.create_group,w.ship_no,o.waybill_id,w.logistics_waybill,l.company logistics_name,cu.type,o.remark,o.create_user')
            ->find();
        if ($order['type']==0){
            $order['type_text']='普通用户';
        }else if ($order['type']==1){
            $order['type_text']='累计消费会员';
        }else{
            $order['type_text']='充值会员';
        }
        try {
            $order['logistics_status_text'] = $order->ShipStatusText;
        }catch (Exception $e){
            trace($e->getMessage(),'error');
        }
        return $order;
    }

    public static function getOrderByIds($ids): array
    {
        $order=new self();

        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');
        if(!empty($group)){
            $where['create_group']=['=',$group];
        }
        if(!empty($search_user)) {
            $where['create_user'] = ['in', $search_user];
        }
        $where['del_flag']=['=',0];
        $where['order_status']=['=',1];
        $where['id']=['in',$ids];
        $where['pay_type']=['in',[0,1,2,3]];
        $orders= $order->where($where)
            ->field('id,customer_id,logistics_status,receipt_number,user_name,items_price,total_price,ship_fee,pay_type,amount_discount,create_group')->order('create_time')->select()->toArray();
        return $orders;
    }

    public static function crateInvoice($id,$invoice_id,$total_price): array
    {
        $OrderClass=new self();
        $OrderHistoryClass=new OrderHistory();

        $OrderClass->startTrans();
        try{
            $result=$OrderClass->where('id',$id)->update(['receipt_number'=>$invoice_id,'pay_type'=>2]);
            if($result===false){
                return ['status'=>false,'result'=>'创建失败'];
            }

            $result=$OrderHistoryClass->insert(['order_id'=>$id,'operator'=>session('Login_user')['id'],'operational'=>'创建账单.'.$total_price.'USD']);
            if($result===false){
                return ['status'=>false,'result'=>'创建历史记录失败'];
            }

            $OrderClass->commit();
            return ['status'=>true,'result'=>'创建成功'];
        }catch (\Exception $e) {
            $OrderClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'创建失败'.$e->getMessage()];
        }
    }

    public static function updateInvoice($id): array
    {
        $OrderClass = new self();
        $OrderItemClass=new OrderItem();

        $order=self::getOrderById($id);
        $items=$OrderItemClass::getOrderItemsById($id);
        $order['items']=$items;

        ['status'=>$status,'result'=>$result]=PaypalApi::updateInvoice($order);
        if($status===false){
            return ['status'=>false,'result'=>$result];
        }
        $pay_status=$result['status'];
        switch ($pay_status){
            case 'DRAFT': $pay_status=1;
                break;
            case 'SENT': $pay_status=2;
                break;
            case 'PARTIALLY_PAID': $pay_status=3;
                break;
            case 'PAID':
            case 'MARKED_AS_PAID': $pay_status=4;
                break;
            default:
                trace('Exception Error.Unknown paypal pay_type.'. json_encode($pay_status),'error');
                $pay_status=$order['pay_type'];
        }
        $result = $OrderClass->where('id', $id)->update(['pay_type' => $pay_status]);

        if ($result === false) {
            return ['status' => false, 'result' => '更新失败'];
        }
        if($pay_status===4){
            ['status'=>$status,'result'=>$stockResult]=Product::lockStockByOrder($id);
            if($status===false){
                return ['status' => true, 'result' => '更新成功，锁定库存失败'.$stockResult];
            }
        }
        return ['status' => true, 'result' => '更新成功'];
    }

    public static function sentInvoice($id): array
    {
        $OrderClass=new self();
        $OrderHistoryClass=new OrderHistory();

        $old_order=$OrderClass->where('id','=',$id)->where('pay_type','=',1)->field('id,receipt_number,create_group')->find();
        if(empty($old_order)){
            return ['status'=>false,'result'=>'未找到可发送的账单'];
        }
        $receipt_number=$old_order['receipt_number'];

        $OrderClass->startTrans();
        try{
            ['status'=>$status,'result'=>$result]=PaypalApi::sentInvoice($receipt_number,$old_order['create_group']);
            if($status===false){
                return ['status'=>false,'result'=>$result];
            }

            $result=$OrderClass->where('id',$id)->update(['pay_type'=>2]);
            if($result===false){
                return ['status'=>false,'result'=>'更新发送状态失败'];
            }

            $result=$OrderHistoryClass->insert(['order_id'=>$id,'operator'=>session('Login_user')['id'],'operational'=>'发送账单信息']);
            if($result===false){
                return ['status'=>false,'result'=>'更新历史记录失败'];
            }

            $OrderClass->commit();
            return ['status'=>true,'result'=>'更新成功'];
        }catch (\Exception $e) {
            $OrderClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新失败'.$e->getMessage()];
        }
    }

    public static function updateOrderCheckData($id): array
    {
        $OrderClass=new self();
        $OrderItemClass=new OrderItem();

        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');
        if(!empty($group)){
            $where['create_group']=['=',$group];
        }

        if(!empty($search_user)) {
            $where['create_user'] = ['in', $search_user];
        }
        $where['del_flag'] = ['=', 0];
        $where['id'] = ['=', $id];
        $where['pay_type'] = ['in', [0,1,2,3,4]];
        $where['order_status'] = ['=', 1];
        $old_order=$OrderClass
            ->where($where)
            ->field('id,total_price,pay_type,customer_id,user_name,curr_type,email,cc_email,country,city,address,zip_code,phone,tip,payment_type,partial_pay,ship_fee,create_user,create_group')
            ->find();
        if(empty($old_order)){
            return ['status'=>false,'result'=>'订单不可更新'];
        }
        $old_order_item=$OrderItemClass
            ->where('order_id',$id)
            ->where('del_flag',0)
            ->field('pro_id,amount,gift,id,selling_price')
            ->select()
            ->toArray();
        if(empty($old_order_item)){
            return ['status'=>false,'result'=>'订单商品未找到'];
        }
        return ['status'=>true,'result'=>['order'=>$old_order,'items'=>$old_order_item]];
    }

    public static function updateOrderWithInvoice($id,$update_order,$sql_data,$pro_ids):array
    {
        [$insert_items,$insert_items_detail,$update_items,$update_items_detail,$gift_item,$gift_item_detail,$update_gift,$update_gift_detail,$delete_items,$delete_gift]=$sql_data;
        $OrderClass=new self();
        $OrderItemClass=new OrderItem();
        $OrderHistoryClass=new OrderHistory();
        $OrderItemDetailClass=new OrderItemDetail();
        $ProductClass=new Product();

        $check=false;
        $insert_order_items_detail=[];
        $update_order_items_detail=[];
        $delete_order_items_detail=[];

        $OrderClass->startTrans();
        try{
            $old_order=$OrderClass->where('id',$id)->where('del_flag',0)->field('pay_type')->find();
            if(empty($old_order)){
                throw Exception('未找到订单');
            }
            $old_item_data=$OrderItemClass->where('order_id',$id)->where('del_flag',0)->lock(true) ->field('amount,demand_stock,pro_id,id')->select()->toArray();
            $old_item_list=[];
            $old_item_id=[];
            foreach ($old_item_data as $key=>$value){
                if(!$value['pro_id']){
                    $old_item_id[]=$value['id'];
                }else{
                    $pro_ids[]=$value['pro_id'];
                }
                if(isset($old_item_list[$value['pro_id']])){
                    $old_item_list[$value['pro_id']]['amount']+=$value['amount'];
                    $old_item_list[$value['pro_id']]['demand_stock']+=$value['demand_stock'];
                    continue;
                }
                $old_item_list[$value['pro_id']]['amount']=$value['amount'];
                $old_item_list[$value['pro_id']]['demand_stock']=$value['demand_stock'];
            }
            if(!empty($old_item_id)) {
                $old_item_detail_list = $OrderItemDetailClass->where('order_item_id', 'in', $old_item_id)->where('del_flag', 0)->lock(true)->group('pro_id')->column('sum(amount) amount,sum(demand_stock) demand_stock', 'pro_id');
                $old_pro_ids = array_keys($old_item_detail_list);
                $pro_ids = array_unique(array_merge($pro_ids, $old_pro_ids));
            }
            $stock_list=$ProductClass->where('id','in',$pro_ids)->lock(true)->column('amount,demand_stock,locked_demand_stock,type','id');
            foreach ($stock_list as $key=>$value){
                if($value['type']===1) {
                    if (isset($old_item_list[$value['id']])) {
                        $value['demand_stock'] -= $old_item_list[$value['id']]['amount'];
                        $value['locked_demand_stock'] -= $old_item_list[$value['id']]['demand_stock'];
                    }
                    if (isset($old_item_detail_list[$value['id']])) {
                        $value['demand_stock'] -= $old_item_detail_list[$value['id']]['amount'];
                        $value['locked_demand_stock'] -= $old_item_detail_list[$value['id']]['demand_stock'];
                    }
                }
                $stock_list[$key]=$value;
            }
            $result=$OrderClass->where('id',$id)->update($update_order);
            if($result===false){
                throw Exception('更新订单失败');
            }
            if($result>0){
                $check=true;
            }

            if(!empty($update_gift)) {
                foreach ($update_gift as $key=>$value){
                    if($value['pro_id']) {
                        $arr =& $stock_list[$value['pro_id']];
                        ['demand_stock' => $value['demand_stock'], 'stock_demand_stock' => $arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']] = Common::demandStock($arr, $value['amount']);
                        $update_gift[$key] = $value;
                    }
                }
                $result=$OrderItemClass->isUpdate(true)->saveAll($update_gift);
                if($result===false){
                    throw Exception('更新订单商品失败');
                }
                foreach ($result as $key=>$value) {
                    if (!empty($update_gift_detail[$key])) {
                        foreach ($update_gift_detail[$key] as $i => $item) {
                            if(!$item['delete']) {
                                $arr =&$stock_list[$item['pro_id']];
                                ['demand_stock' => $item['demand_stock'], 'stock_demand_stock' => $arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']] = Common::demandStock($arr, $item['amount']);
                                if ($item['id']) {
                                    $item['order_item_id'] = $value['id'];
                                    $insert_order_items_detail[] = $item;
                                } else {
                                    $update_order_items_detail[] = $item;
                                }
                            }else{
                                $item['id'] && $delete_order_items_detail[]=$item['id'];
                            }
                        }
                    }
                }
            }
            foreach ($update_items as $key=>$value) {
                if($value['pro_id']) {
                    $arr =& $stock_list[$value['pro_id']];
                    ['demand_stock' => $value['demand_stock'], 'stock_demand_stock' => $arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']] = Common::demandStock($arr, $value['amount']);
                }
                $result = $OrderItemClass->where('id',$value['id'])->update($value);
                if ($result === false) {
                    throw Exception('更新订单商品失败');
                }
                if(!empty($update_items_detail[$key])) {
                    foreach ($update_items_detail[$key] as $i => $item) {
                        if(!$item['delete']) {
                            $arr =& $stock_list[$item['pro_id']];
                            ['demand_stock' => $item['demand_stock'], 'stock_demand_stock' => $arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']] = Common::demandStock($arr, $item['amount']);
                            if ($item['id']) {
                                $item['order_item_id'] = $value['id'];
                                $insert_order_items_detail[] = $item;
                            } else {
                                $update_order_items_detail[] = $item;
                            }
                        }else{
                            $item['id'] && $delete_order_items_detail[]=$item['id'];
                        }
                    }
                }
                if ($result > 0) {
                    $check = true;
                }
            }

            if(!empty($insert_items)) {
                foreach ($insert_items as $key=>$value){
                    if($value['pro_id']) {
                        $arr =&$stock_list[$value['pro_id']];
                        ['demand_stock'=>$value['demand_stock'],'stock_demand_stock'=>$arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']]=Common::demandStock($arr,$value['amount']);
                        $insert_items[$key]=$value;
                    }
                }
                $result = $OrderItemClass->isUpdate(false)->saveAll($insert_items);
                if ($result === false) {
                    throw Exception('新增订单商品失败');
                }
                foreach ($result as $key=>$value) {
                    if (!empty($insert_items_detail[$key])) {
                        foreach ($insert_items_detail[$key] as $i => $item) {
                            if($item['delete']){
                                continue;
                            }
                            $arr =&$stock_list[$item['pro_id']];
                            ['demand_stock'=>$item['demand_stock'],'stock_demand_stock'=>$arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']]=Common::demandStock($arr,$item['amount']);
                            $item['order_item_id'] = $value->id;
                            $insert_order_items_detail[] = $item;
                        }
                    }
                }
                $check=true;
            }
            if(!empty($gift_item)){
                foreach ($gift_item as $key=>$value){
                    if($value['pro_id']) {
                        $arr =&$stock_list[$value['pro_id']];
                        ['demand_stock'=>$value['demand_stock'],'stock_demand_stock'=>$arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']]=Common::demandStock($arr,$value['amount']);
                        $gift_item[$key]=$value;
                    }
                }
                $result=$OrderItemClass->isUpdate(false)->saveAll($gift_item);
                if($result===false){
                    throw Exception('新增订单礼品失败');
                }
                foreach ($result as $key=>$value) {
                    if (!empty($gift_item_detail[$key])) {
                        foreach ($gift_item_detail[$key] as $i => $item) {
                            if($item['delete']){
                                continue;
                            }
                            $arr =&$stock_list[$item['pro_id']];
                            ['demand_stock'=>$item['demand_stock'],'stock_demand_stock'=>$arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']]=Common::demandStock($arr,$item['amount']);

                            $item['order_item_id'] = $value->id;
                            $insert_order_items_detail[] = $item;
                        }
                    }
                }
            }

            if(!empty($delete_items)) {
                $result = $OrderItemClass->where('id', 'in', $delete_items)->update(['del_flag' => 1,'demand_stock'=>0]);
                $OrderItemDetailClass->where('order_item_id','in',$delete_items)->update(['del_flag'=>1,'demand_stock'=>0]);
                if ($result === false) {
                    throw Exception('删除订单商品');
                }
                if ($result > 0) {
                    $check = true;
                }
            }
            if(!empty($delete_gift)){
                $result=$OrderItemClass->where('id','in',$delete_gift)->update(['del_flag'=>1,'demand_stock'=>0]);
                $OrderItemDetailClass->where('order_item_id','in',$delete_gift)->update(['del_flag'=>1,'demand_stock'=>0]);
                if($result===false){
                    throw Exception('删除订单礼品');
                }
            }

            if(!empty($insert_order_items_detail)){
                $result=$OrderItemDetailClass->allowField(true)->isUpdate(false)->saveAll($insert_order_items_detail);
                if($result===false){
                    throw Exception('新增订单礼品失败');
                }
            }
            if(!empty($update_order_items_detail)){
                $result=$OrderItemDetailClass->allowField(true)->isUpdate(true)->saveAll($update_order_items_detail);
                if($result===false){
                    throw Exception('更新订单礼品失败');
                }
            }
            if(!empty($delete_order_items_detail)){
                $result=$OrderItemDetailClass->where('id','in',$delete_order_items_detail)->save(['del_flag'=>1]);
                if($result===false){
                    throw Exception('删除订单礼品失败');
                }
            }
            $result=$ProductClass->allowField(['id','demand_stock'])->isUpdate(true)->saveAll($stock_list);
            if($result===false){
                throw Exception('更新库存失败');
            }
            $result=$OrderHistoryClass->insert(['order_id'=>$id,'operator'=>session('Login_user')['id'],'operational'=>'更新账单信息,金额：'.round($update_order['total_price']-$update_order['amount_discount'],2).'USD']);
            if($result===false){
                throw Exception('更新订单历史记录失败');
            }

            $OrderClass->commit();
            return ['status'=>true,'result'=>['msg'=>'更新成功','check'=>$check,'old_order'=>$old_order]];
        }catch (\Exception $e) {
            $OrderClass->rollback();
            trace('order save error'.$e->getMessage().' '.$e->getLine(),'error');
            return ['status'=>false,'result'=>'更新失败'.$e->getMessage()];
        }
    }

    public static function createOrderMerge($ids,$order_id,$update_order,$order_items,$order_items_detail): array
    {
        $OrderClass=new self();
        $OrderItemClass=new OrderItem();
        $OrderHistoryClass=new OrderHistory();
        $CustomerOrderClass=new CustomerOrder();
        $OrderItemDetailClass=new OrderItemDetail();

        $OrderClass->startTrans();
        try{
            if($update_order['amount_discount']>0) {
                $customer_discount=CustomerDiscount::where('customer_id', $update_order['customer_id'])->field('id,balance')->find();
                if(!empty($customer_discount)){
                    $use_discount_price=($update_order['amount_discount']-$update_order['old_discount']);
                    $customer_discount['balance']=round($customer_discount['balance']-$use_discount_price,2);
                    if($customer_discount['balance']<0){
                        $use_discount_price=$customer_discount['balance'];
                        $customer_discount['balance']=0;
                    }
                    $result=CustomerDiscount::where('id', $customer_discount['id'])->update(['balance'=>$customer_discount['balance']]);
                    if($result===false){
                        return ['status'=>false,'result'=>'抵扣更新记录失败'];
                    }
                    $result=(new CustomerDiscountHistory)->save(['discount_id'=>$customer_discount['id'],'order_id'=>$order_id,'customer_id'=>$update_order['customer_id'],'price'=>$use_discount_price,'type'=>0,'create_user'=>$update_order['create_user']]);
                    if($result===false){
                        return ['status'=>false,'result'=>'抵扣更新记录失败'];
                    }
                }
            }
            unset($update_order['old_discount']);
            $result=$CustomerOrderClass->where('id','in', $ids)->update(['status'=>1]);
            if($result===false){
                return ['status'=>false,'result'=>'更新已订商品状态失败'];
            }
            $result=$OrderClass->save($update_order,['id'=>$order_id]);
            if($result===false){
                return ['status'=>false,'result'=>'更新订单失败'];
            }
            $result=$OrderItemClass->saveAll($order_items);
            if($result===false){
                return ['status'=>false,'result'=>'新增订单商品失败'];
            }
            $order_items_detail_insert=[];
            foreach ($result as $key=>$value){
                foreach ($order_items_detail[$key] as $item){
                    $item['order_item_id']=$value->id;
                    $order_items_detail_insert[]=$item;
                }
            }
            if(!empty($order_items_detail_insert)) {
                $result = $OrderItemDetailClass->insertAll($order_items_detail_insert);
                if ($result === false) {
                    return ['status' => false, 'result' => '新增订单商品详情失败'];
                }
            }
            $order=Order::getOrderById($order_id);
            $items=OrderItem::getOrderItemsById($order_id);
            $order['items']=$items;

            ['status'=>$status,'result'=>$result]=PaypalApi::updateInvoice($order);
            if($status===false){
                return ['status'=>false,'result'=>$result];
            }

            $result=$OrderHistoryClass->insert(['order_id'=>$order_id,'operator'=>session('Login_user')['id'],'operational'=>'合并账单']);
            if($result===false){
                return ['status'=>false,'result'=>'更新历史记录失败'];
            }

            $OrderClass->commit();
            return ['status'=>true,'result'=>'合并成功'];
        }catch (\Exception $e) {
            $OrderClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'合并失败'.$e->getMessage()];
        }
    }

    /**
     * getPaymentById
     *
     * @url
     * @method
     * @param $id
     * @return array|bool|false|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/1/5
     */
    public static function getPaymentById($id){
        $OrderClass=new self();
        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');
        if(!empty($group)){
            $where['o.create_group']=['=',$group];
        }

        if(!empty($search_user)) {
            $where['o.create_user'] = ['in', $search_user];
        }
        $where['o.id']=['=',$id];
        $where['o.order_status']=['=',1];
        $where['o.del_flag']=['=',0];
        $where['o.pay_type']=['in',[2,3]];
        $data=$OrderClass->alias('o')
            ->join('customer c','o.customer_id=c.id','left')
            ->join('member m','o.customer_id=m.customer_id and m.del_flag=0','left')
            ->where($where)
            ->field('o.id,o.receipt_number,o.items_price,o.ship_fee,o.total_price,o.pay_type,o.payment_type,o.partial_pay,IFNULL(o.amount_discount,0) amount_discount,o.amount_paid,o.tip_paid,o.create_group,o.customer_id,c.type,m.card_id,m.id member_id,m.balance')
            ->find();
        return $data;
    }

    /**
     * getPaidOrderPaidCost
     * 获得所有账单金额和已付款金额
     * @url
     * @method
     * @param array $search_param 搜索条件
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/1/14
     */
    public static function  getPaidOrderPaidCost($search_param): array
    {
        $OrderClass=new self();
        $where['o.del_flag']=['=',0];
        $where['o.create_user']=['<>',0];
        $where['oi.del_flag']=['=',0];
        $where['oi.gift']=['=',0];
        $where['oi.create_user']=['<>',0];

        ['action_role'=>$action_role,'search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('report_paid');
        if(!empty($group)){
            $where['oi.create_group']=['=',$group];
        }else if (is_numeric($search_param['group_id']) && $search_param['group_id']) {
            $where['oi.create_group'] = ['=', $search_param['group_id']];
        }

        if(!empty($search_user)) {
            $where['oi.create_user'] = ['in', $search_user];
        }else if(is_array($search_param['user']) && !empty($search_param['user'])){
            $search_user=$search_param['user'];
            $where['oi.create_user'] = ['in', $search_user];
        }

        if (!empty($search_param['create_time'])) {
            $where['o.payment_time']=['between',[$search_param['create_time'][0].' 00:00:00',$search_param['create_time'][1].' 23:59:59']];
        }
        $condition=[4,6,7];
        $obj=$OrderClass->alias('o')
            ->join('order_item oi','o.id=oi.order_id','left')
            ->join('__USER__ u','oi.create_user=u.id','left')
            ->where($where)
            ->where('o.pay_type','in',$condition)
            ->field('round(sum((o.amount_paid-o.tip_paid-o.ship_fee)*(oi.selling_price/o.items_price)), 2) price,u.user_name user,oi.create_user')
            ->group('oi.create_user')
            ->order('price','desc')
            ->select();
        if(is_null($obj)){
            $cost=0;
        }else{
            $cost=$obj->toArray();
        }

        $cost_list=[];
        if($cost!==0){
            foreach ($cost as $key=>$value){
                $cost_list[]=['total_price'=>$order_cost_list[$value['create_user']]['price']??0,'user'=>$value['user'],'price'=>$value['price'],'create_user'=>$value['create_user']];
            }
        }

        return ['status'=>true,'result'=>['cost'=>$cost_list,'action_role'=>$action_role]];
    }

    /**
     * 获取担任的回款清单
     * create by yhb on 2021/3/22 17:26
     * @param $search_param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderDetail($search_param)
    {
        $OrderClass=new self();
        $where['o.del_flag']=['=',0];
        $where['o.create_user']=['<>',0];
        $where['oi.del_flag']=['=',0];
        $where['oi.gift']=['=',0];
        $where['oi.create_user']=['<>',0];
        ['action_role'=>$action_role,'search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('report_paid');
        if(!empty($group)){
            $where['oi.create_group']=['=',$group];
        }else if (is_numeric($search_param['group_id']) && $search_param['group_id']) {
            $where['oi.create_group'] = ['=', $search_param['group_id']];
        }

        if(!empty($search_user)) {
            $where['oi.create_user'] = ['in', $search_user];
        }else if(is_array($search_param['user']) && !empty($search_param['user'])){
            $search_user=$search_param['user'];
            $where['oi.create_user'] = ['in', $search_user];
        }

        if (!empty($search_param['create_time'])) {
            $where['o.payment_time']=['between',[$search_param['create_time'][0].' 00:00:00',$search_param['create_time'][1].' 23:59:59']];
        }

        $condition=[4,6,7];
        $obj=$OrderClass->alias('o')
            ->join('order_item oi','o.id=oi.order_id','left')
            ->join('__USER__ u','oi.create_user=u.id','left')
            ->where('o.pay_type','in',$condition)
            ->where($where)
            ->where('oi.create_user',$search_param['id'])
            ->field('round((o.amount_paid-o.tip_paid-o.ship_fee)*(oi.selling_price/o.items_price), 2) price,o.order_id,o.user_name,oi.en_name')
            ->order('price','desc')
            ->select();
        if(!empty($obj)){
            $order_detail = $obj->toArray();
        }else{
            return [];
        }
        return ['status'=>true,'result'=>['order_detail'=>$order_detail,'action_role'=>$action_role]];
    }

    /**
     * splitInvoice
     * 拆分订单
     * @url
     * @method
     * @param int $id 账单ID
     * @param array $order 旧账单商品数据
     * @param array $new_order 新账单商品数据
     * @param array $update_order 旧账单更新数据
     * @param array $insert_new_order 新账单数据
     * @return array|null
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/1/13
     */
    public static function splitInvoice($id, $order, $new_order, $update_order, $insert_new_order,$pro_ids): array
    {
        $OrderClass=new self();
        $OrderItemClass=new OrderItem();
        $OrderItemDetailClass=new OrderItemDetail();
        $OrderHistoryClass=new OrderHistory();
        $ProductClass=new Product();
        $OrderClass->startTrans();
        try{
            $old_item_data=$OrderItemClass->where('order_id',$id)->where('del_flag',0)->lock(true) ->field('amount,demand_stock,pro_id,id')->select()->toArray();
            $old_item_list=[];
            $old_item_id=[];
            foreach ($old_item_data as $key=>$value){
                if(!$value['pro_id']){
                    $old_item_id[]=$value['id'];
                }else{
                    $pro_ids[]=$value['pro_id'];
                }
                if(isset($old_item_list[$value['pro_id']])){
                    $old_item_list[$value['pro_id']]['demand_stock']+=$value['demand_stock'];
                    $old_item_list[$value['pro_id']]['amount']+=$value['amount'];
                    continue;
                }
                $old_item_list[$value['pro_id']]['demand_stock']=$value['demand_stock'];
                $old_item_list[$value['pro_id']]['amount']=$value['amount'];
            }
            if(!empty($old_item_id)) {
                $old_item_detail_list = $OrderItemDetailClass->where('order_item_id', 'in', $old_item_id)->where('del_flag', 0)->lock(true)->group('pro_id')->column('sum(amount) amount,sum(demand_stock) demand_stock', 'pro_id');
                $old_pro_ids = array_keys($old_item_detail_list);
                $pro_ids = array_unique(array_merge($pro_ids, $old_pro_ids));
            }
            $stock_list=$ProductClass->where('id','in',$pro_ids)->lock(true)->column('amount,demand_stock,locked_demand_stock,type','id');
            foreach ($stock_list as $key=>$value){
                if($value['type']===1){
                    if(isset($old_item_list[$value['id']])){
                        $value['demand_stock']-=$old_item_list[$value['id']]['amount'];
                        $value['locked_demand_stock']-=$old_item_list[$value['id']]['demand_stock'];
                    }
                    if(isset($old_item_detail_list[$value['id']])){
                        $value['demand_stock']-=$old_item_detail_list[$value['id']]['amount'];
                        $value['locked_demand_stock']-=$old_item_detail_list[$value['id']]['demand_stock'];
                    }
                }
                $stock_list[$key]=$value;
            }

            $result=$OrderClass->isUpdate()->save($update_order,['id'=>$id]);
            if($result===false){
                throw new RuntimeException('更新账单失败');
            }

            $result=$OrderClass->isUpdate(false)->save($insert_new_order);
            if($result===false){
                throw new RuntimeException('新账单创建失败');
            }
            $order_id=$OrderClass->id;

            $result=$OrderHistoryClass->isUpdate(false)->saveAll([
                ['order_id'=>$id,'operator'=>session('Login_user')['id'],'operational'=>'拆分订单'],
                ['order_id'=>$order_id,'operator'=>session('Login_user')['id'],'operational'=>'拆分订单']
            ]);
            if($result===false){
                throw new RuntimeException('增加历史失败');
            }

            $insert=[];
            $update=[];
            $delete=[];
            if(!empty($order['insert'])){
                $insert=array_merge($insert,$order['insert']);
            }
            if(!empty($order['update'])){
                $update=array_merge($update,$order['update']);
            }
            if(!empty($order['delete'])){
                $delete=array_merge($delete,$order['delete']);
            }
            if(!empty($order['gift_item'])){
                $insert=array_merge($insert,$order['gift_item']);
            }
            if(!empty($order['update_gift'])){
                $update=array_merge($update,$order['update_gift']);
            }
            if(!empty($order['delete_gift'])){
                $delete=array_merge($delete,$order['delete_gift']);
            }

            foreach ($new_order['insert'] as $key=>$value){
                $new_order['insert'][$key]['order_id']=$order_id;
            }
            $insert=array_merge($insert,$new_order['insert']);

            if(!empty($new_order['gift_item'])){
                foreach ($new_order['gift_item'] as $key=>$value){
                    $new_order['gift_item'][$key]['order_id']=$order_id;
                }
                $insert=array_merge($insert,$new_order['gift_item']);
            }
            $detail=[];
            foreach ($insert as $key=>$value){
                if($value['pro_id']) {
                    $arr =&$stock_list[$value['pro_id']];
                    ['demand_stock'=>$value['demand_stock'],'stock_demand_stock'=>$arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']]=Common::demandStock($arr,$value['amount']);
                    unset($value['children']);
                    $insert[$key]=$value;
                }else{
                    if(isset($value['children'])) {
                        $detail[$key] = $value['children'];
                    }
                }
                unset($insert[$key]['children']);
            }
            $result=$OrderItemClass->isUpdate(false)->saveAll($insert);
            if($result===false){
                throw new RuntimeException('新增商品失败');
            }
            $insert_detail=[];
            foreach ($result as $key=>$value){
                if(isset($detail[$key])) {
                    foreach ($detail[$key] as $i => $item) {
                        if ($item['delete']) {
                            continue;
                        }
                        $arr =& $stock_list[$item['pro_id']];
                        ['demand_stock' => $item['demand_stock'], 'stock_demand_stock' => $arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']] = Common::demandStock($arr, $item['amount']);
                        $item['order_item_id'] = $value->id;
                        $insert_detail[] = $item;

                    }
                }
            }

            if(!empty($update)) {
                $update_detail=[];
                $delete_detail=[];
                foreach ($update as $key=>$value){
                    if($value['pro_id']) {
                        $arr =&$stock_list[$value['pro_id']];
                        ['demand_stock'=>$value['demand_stock'],'stock_demand_stock'=>$arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']]=Common::demandStock($arr,$value['amount']);
                        unset($value['children']);
                        $update[$key]=$value;
                    }else{
                        if(isset($value['children'])) {
                            foreach ($value['children'] as $i => $item) {
                                if (!$item['delete']) {
                                    $arr =& $stock_list[$item['pro_id']];
                                    ['demand_stock' => $item['demand_stock'], 'stock_demand_stock' => $arr['demand_stock'], 'stock_locked_demand_stock' => $arr['locked_demand_stock']] = Common::demandStock($arr, $item['amount']);
                                    if ($item['id']) {
                                        $update_detail[] = $item;
                                    } else {
                                        $item['order_item_id'] = $value['id'];
                                        $insert_detail[] = $item;
                                    }
                                } else {
                                    $item['id'] && $delete_detail[] = $item['id'];
                                }
                            }
                        }
                    }
                    unset($update[$key]['children']);
                }
                $result=$OrderItemClass->isUpdate()->saveAll($update);
                if($result===false){
                    throw new RuntimeException('更新商品失败');
                }

                if(!empty($update_detail)) {
                    $result = $OrderItemDetailClass->allowField(true)->isUpdate()->saveAll($update_detail);
                    if ($result === false) {
                        throw new RuntimeException('新增商品详情失败');
                    }
                }

                if(!empty($delete_detail)) {
                    $result = $OrderItemDetailClass->where('id','in',$delete_detail)->update(['del_flag'=>1]);
                    if ($result === false) {
                        throw new RuntimeException('删除商品详情失败');
                    }
                }
            }
            if(!empty($insert_detail)) {
                $result = $OrderItemDetailClass->allowField(true)->isUpdate(false)->saveAll($insert_detail);
                if ($result === false) {
                    throw new RuntimeException('新增商品详情失败');
                }
            }
            if(!empty($delete)) {
                $result=$OrderItemClass->where('id','in',$delete)->update(['del_flag'=>1]);
                if($result===false){
                    throw new RuntimeException('更新商品失败');
                }
            }
            $result=$ProductClass->allowField(['id','demand_stock'])->isUpdate(true)->saveAll($stock_list);
            if($result===false){
                throw new RuntimeException('更新库存失败');
            }
            ['status'=>$status,'result'=>$result]=self::updateInvoice($id);
            if($status===false){
                throw new RuntimeException($result);
            }
            $OrderClass->commit();
            return ['status'=>true,'result'=>['msg'=>'拆分成功','id'=>$order_id]];
        }catch (RuntimeException $e){
            $OrderClass->rollback();
            trace('拆分失败 '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'拆分失败 '.$e->getMessage()];
        }
    }

    public static function getOrderByPro($pro_id,$oid)
    {
        $orderClass=new self();
        $orderItemClass=new OrderItem();
        $where['o.del_flag']=0;
        $where['oi.del_flag']=0;
        $where['oi.pro_id']=$pro_id;
        $where['oi.lock_quantity']=['>',0];
        $where['oi.id']=['<>',$oid];
        $data=$orderClass->alias('o')
            ->join('order_item oi','o.id=oi.order_id','left')
            ->join('customer c','c.id=o.customer_id','left')
            ->where($where)
            ->where('o.waybill_id',null)
            ->field('oi.id,o.order_id,c.customer_name,oi.lock_quantity,o.payment_time')
            ->order('o.payment_time desc')
            ->select();
        return ['status'=>true,'result'=>['data'=>$data]];
    }

    public static function remarkOrder($id,$remark){
        $OrderClass=new self();
        $OrderHistoryClass=new OrderHistory();
        $OrderClass->startTrans();
        try {
            $result = $OrderClass->where('id', $id)->update(['remark' => $remark]);
            if($result===false){
                throw new RuntimeException('增加备注失败');
            }
            $result=$OrderHistoryClass->isUpdate(false)->save(['order_id'=>$id,'operator'=>session('Login_user')['id'],'operational'=>'备注订单 '.$remark]);
            if($result===false){
                throw new RuntimeException('增加历史失败');
            }
            $OrderClass->commit();
            return ['status'=>true,'result'=>'备注成功'];
        }catch (Exception $e){
            $OrderClass->rollback();
            trace('备注失败 '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'备注失败 '.$e->getMessage()];
        }
    }
}